package com.example.yuejian11.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.yuejian11.R;
import com.example.yuejian11.adapter.STCommentAdapter;
import com.example.yuejian11.bean.STCommentEntity;
import com.example.yuejian11.bean.STEntity;
import com.example.yuejian11.common.GlideImageLoader;
import com.example.yuejian11.common.Url;
import com.example.yuejian11.view.TitleView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

public class STDetailActivity extends BaseActivity {


    private static final String TAG = "STDetailActivity";
    @BindView(R.id.title_activity)
    TitleView titleView;
    @BindView(R.id.img)
    ImageView imageView;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.recy)
    RecyclerView recy;
    Handler handler_activity = new mHandler();
    RecyclerView.Adapter adapter;
    LinearLayoutManager layoutManager;
    private String sid;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_stdetail);
        super.onCreate(savedInstanceState);

        initView();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    private void initView() {
        context = getBaseContext();
        sid = getIntent().getIntExtra("sid", 0) + "";
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用

        titleView.getLeftBackTextTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.finishActivity(STDetailActivity.class);
            }
        });

        titleView.getRightTextTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(STDetailActivity.this, CommentActivity.class);
                intent.putExtra("sid", sid);
                ActivityUtils.startActivity(intent);
            }
        });
    }

    private void initData() {

        EasyHttp.get("yuejian6/public/index.php/json/slideshow/details").params("show_id", sid)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String data) {

                        Message msg = Message.obtain(); // 实例化消息对象
                        msg.what = 0; // 消息标识
                        msg.obj = data; // 消息内容存放

                        handler_activity.sendMessage(msg);
                    }

                    @Override
                    public void onError(ApiException error) {
                        Log.d(TAG, "onFailed: " + error);
                    }
                });


        EasyHttp.get("yuejian6/public/index.php/json/slideshow/comment").params("show_id", sid)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String data) {

                        Message msg = Message.obtain(); // 实例化消息对象
                        msg.what = 1; // 消息标识
                        msg.obj = data; // 消息内容存放

                        handler_activity.sendMessage(msg);
                    }

                    @Override
                    public void onError(ApiException error) {
                        Log.d(TAG, "onFailed: " + error);
                    }
                });

    }

    class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    STEntity stEntities = null;

                    try {
                        stEntities = JSON.parseObject(msg.obj.toString(), STEntity.class);
                    } catch (Exception e) {
                        ToastUtils.showShort("获取数据失败");
                        return;
                    }

                    String pic = stEntities.getPic();
                    if (StringUtils.isEmpty(pic)) {
                        return;
                    }
                    String[] split = pic.split("#");

                    List<String> imgs = Arrays.asList(split);

                    List<String> arrayList = new ArrayList();
                    for (int i = 0; i < imgs.size(); ++i) {
                        imgs.set(i, Url.imgUrl + imgs.get(i));
                        arrayList.add("");
                    }

                    //设置图片集合
                    banner.setBannerTitles(arrayList);
                    banner.setImages(imgs);
                    banner.start();

                    name.setText(stEntities.getNickname());
                    time.setText(stEntities.getOpentime());

                    Glide.with(context).load(Url.imgUrl + stEntities.getUser_pic()).into(imageView);


                    break;
                case 1:

                    List<STCommentEntity> commentEntities = null;

                    try {
                        commentEntities = JSON.parseArray(msg.obj.toString(), STCommentEntity.class);
                    } catch (Exception e) {
                        ToastUtils.showShort("数据获取失败");
                        return;
                    }
                    layoutManager = new LinearLayoutManager(context);
                    adapter = new STCommentAdapter(context, commentEntities, R.layout.comment_item);
                    //设置布局管理器
                    recy.setLayoutManager(layoutManager);
//设置为垂直布局，这也是默认的
                    layoutManager.setOrientation(OrientationHelper.VERTICAL);
//设置Adapter
                    recy.setAdapter(adapter);
//设置增加或删除条目的动画
                    recy.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
                    recy.setItemAnimator(new DefaultItemAnimator());


                    break;
            }
        }
    }
}
